import requests
import html
from htmlParser import MyHtmlParser
import configparser

url = "http://www.ivsky.com/tupian/"
cf = configparser.ConfigParser()
cf.read("test.conf")


def get_pic():
    print("开始获取图片。。。。。。。")
    for x in range(100):
        # 请求地址
        r = requests.get(url + "index_" + str(x + 1) + ".html")
        print(r.text)
        # html转换器，需要继承HTMLParser,并实现3个方法
        parser1 = MyHtmlParser()
        parser1.feed(r.text)
        # 获取本次请求的获得的所有图片地址
        for img in parser1.imgArr:
            if not img.startswith("http:"):
                img = "http:" + img
            print(img)
            # 写文件到本地
            write_file(img)


def write_file(img):
    r = requests.get(img)
    # 获取文件名称
    filename = img.split("/")[-1]
    print("文件名称：", filename)
    # 写文件
    file = open(get_img_dir() + filename, "wb")
    file.write(r.content)


def get_img_dir():
    return cf.get("dir", "imgDir")


if __name__ == "__main__":
    get_pic()
